package com.baidu.translate.demo;


import net.sf.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TransApi {
    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";

    private String appid;
    private String securityKey;

    public TransApi(String appid, String securityKey) {
        this.appid = appid;
        this.securityKey = securityKey;
    }

    public static TransApi getInstance() {
        return new TransApi("20161215000034085", "UBa1SuK1mtHw0CGz8U3Z");
    }

    public String getTransResult(String query, String from, String to) {
        Map<String, String> params = buildParams(query, from, to);
        return HttpGet.get(TRANS_API_HOST, params);
    }

    public String trans2en(String query) {
        return trans(query, "en");
    }

    public String trans2zh(String query) {
        return trans(query, "zh");
    }

    public String trans(String query, String to) {
        String transResult = getTransResult(query, "auto", to);
        JSONObject jsonObject = JSONObject.fromObject(transResult);
        List<Map<String, String>> mapList = (List<Map<String, String>>) jsonObject.get("trans_result");
        if (null != mapList) {
            Map<String, String> map = mapList.get(0);
            return map.get("dst");
        } else {
            return "";
        }
    }

    private Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);

        params.put("appid", appid);

        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);

        // 签名
        String src = appid + query + salt + securityKey; // 加密前的原文
        params.put("sign", MD5.md5(src));

        return params;
    }

}
